package com.stark.commons.spring.web.support.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConversionException;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;

/**
 * {@link HttpMessageConversionException} 异常处理器。
 * <p>返回 <code>400</code>状态码及错误信息。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
public class HttpMessageConversionExceptionHandler implements ExceptionHandler {
	
	@Override
	public boolean instanceofException(Exception ex) {
		return ex instanceof HttpMessageConversionException;
	}

	@Override
	public ResponseEntity<String> handle(Exception ex) {
		HttpMessageConversionException hmcEx = (HttpMessageConversionException) ex;
		String errmsg = "参数类型转换错误:";
		
		// jackson 参数转换错误
		if (hmcEx.getRootCause() instanceof InvalidFormatException) {
			InvalidFormatException e = (InvalidFormatException) hmcEx.getRootCause();
			errmsg += "\n" + e.getPath().get(0).getFieldName() + ": \"" + String.valueOf(e.getValue()) + "\" 无法转换为 " + e.getTargetType() + " 类型";
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errmsg);
		}
		
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errmsg + hmcEx.getMessage());
	}

}
